/*
 * Sudoku.cpp
 *
 *  Created on: Sep 28, 2009
 *      Author: Cha
 */
#include "Sudoku.h"
#include <cstdlib>
#include <fstream>
using namespace std;
 
#define DIMEN 9
#define TOTAL_GRIDS DIMEN*DIMEN

Sudoku::Sudoku(){
	/*init the board. It has a length of 81, and stores
	 the 2-d sudoku board in a 1-d array.*/
	boardArray = new sudokuGrid*[TOTAL_GRIDS];
}

void Sudoku::initGame(int difficulty){
	/*initialize all the elements in the array*/
	for(int x = 0; x < TOTAL_GRIDS; x++){
		sudokuGrid *new_elem = (sudokuGrid *)malloc(sizeof(struct sudokuGrid));
		initGrid(new_elem, x);
		insertGrid(new_elem, x);
	}
		
	ifstream indata;
	int grid_index, val;
	switch(difficulty){
	case 1:
		indata.open("easySudoku.txt");
		break;
	case 2:
		indata.open("medSudoku.txt");
		break;
	case 3:
		indata.open("hardSudoku.txt");
		break;
	}
	while(!indata.eof()){
		indata >> grid_index >> val;
		setGridValue(boardArray[grid_index], val);
	}
	indata.close();	
	

}

void Sudoku::initGrid(sudokuGrid *cur, int index){
	/*-1 means the grid is clear*/
	cur->actual_value = -1;
	cur->board_index = index;
	/*fill the possible values array with 1-9*/
	cur->possible_values = new int[9];
	for(int val = 1; val < 10; val++)
		cur->possible_values[val - 1] = val;
}

void Sudoku::insertGrid(sudokuGrid *cur, int index){
	boardArray[index] = cur;
}

sudokuGrid* Sudoku::getGrid(int index){
	return boardArray[index];
}

int Sudoku::getNextPossibleValue(sudokuGrid *elem){
	for(int i = 0; i < 9; i++){
		if(elem->possible_values[i] != 0){
			return elem->possible_values[i];
		}
	}
	return -1;
}

void Sudoku::restorePossibleValues(sudokuGrid *elem){
	for(int val = 1; val < 10; val++)
		elem->possible_values[val - 1] = val;
}


void Sudoku::purgeValue(sudokuGrid *elem, int del_val ){
	//if(elem->actual_value == -1)
		elem->possible_values[del_val - 1] = 0;
}

void Sudoku::restoreValue(sudokuGrid *elem, int res_val ){
	elem->possible_values[res_val - 1] = res_val;
}

//checks to see if there is one remaining value in the array, if so, the grid is set to that value
void Sudoku::checkForAnswer(sudokuGrid *elem){
	for(int i = 0; i < 9; i++){
		//if( elem->possible_values[i];
	}
}

void Sudoku::setGridValue(sudokuGrid *target, int value){
	target->actual_value = value;
}
